package avaliacao.visao;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import avaliacao.modelo.Produto;

/**
 * Servlet implementation class CarrinhoDeCompra
 */
@WebServlet("/carrinhoDeCompra")
public class CarrinhoDeCompra extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CarrinhoDeCompra() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		@SuppressWarnings("unchecked")
		Map<Integer, Produto> carrinho = (Map<Integer, Produto>) session.getAttribute("carrinho");
		
		PrintWriter out = response.getWriter();
		response.setContentType("text/html");
		out.println("<!DOCTYPE html>\n"+
					"<html>\n"+
					"<head>\n"+
					"<meta charset=\"utf-8\">\n"+
					"<title>Carrinho de compras</title>\n"+
					"</head>\n"+
					"<body>\n"+
					"<h2>Produtos no Carrinho de Compras</h2>\n"+ 
					"<table border=\"1\">\n"+
					"<tr>\n"+
					"<th>Código</th>\n"+
					"<th>Produto</th>\n"+
					"<th>Preço</th>\n"+
					"</tr>\n");
		double total = 0;
		Iterator<Produto> itCarrinho = carrinho.values().iterator(); 
		while ( itCarrinho.hasNext() ) {
			Produto p = itCarrinho.next();
			out.println("<tr><td align=\"center\">"+p.getCodigo()+"</td>\n"+
						"<td>"+p.getNome()+"</td>\n"+
						"<td align=\"center\">"+p.getPreco()+"</td>");
			total += p.getPreco();
		}
		out.println("<tr><th colspan=\"2\">TOTAL (R$)</th><th>"+total+"</th></tr>\n"+
					"</table>\n"+
					"<a href=\"/AvaliacaoServlet\">&lt;&lt;&lt; Voltar</a>\n"+
					"</body>\n"+
					"</html>\n");
	}

}
